from flask import render_template, g, redirect, url_for, request, jsonify, current_app, session

from info import response_code, db, constants
from info.models import Category, News
from info.modules.user import user_blue
from info.utils.comment import user_login_data
from info.utils.file_storage import upload_file


@user_blue.route('/news_list')
@user_login_data
def user_news_list():
    """用户发布的新闻"""
    # 1.获取登录用户信息
    user = g.user
    if not user:
        # 如果用户未登录，重定向到index蓝图中的index视图
        return redirect(url_for('index.index'))

    # 2.获取参数(用户看第几页)
    page = request.args.get('p', 1)

    # 3.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 4.查询用户发布的新闻列表
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_LIST_MAX_NEWS, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
    # 5.构造响应数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    context = {
        'news_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    # 6.渲染用户发布的新闻模板
    return render_template('news/user_news_list.html', context=context)


@user_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    """新闻发布
    1.查询登录用户基本信息
    2.展示新闻发布界面：GET
    3.实现新闻发送逻辑：POST
    """
    # 1.查询登录用户基本信息
    user = g.user
    if not user:
        # 如果用户未登录，重定向到index蓝图中的index视图
        return redirect(url_for('index.index'))

    # 2.展示新闻发布页面逻辑：GET
    if request.method == 'GET':
        # 2.1查询和渲染新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 2.2去掉'最新'标签
        categories.pop(0)

        # 2.3构造渲染数据
        context = {
            'categories': categories
        }
        # 2.4渲染界⾯面
        return render_template('news/user_news_release.html', context=context)

    # 3.实现新闻发送逻辑：POST
    if request.method == 'POST':

        # 3.1 获取参数
        title = request.form.get("title")
        source = "个⼈发布"
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

        # 3.2 校验参数
        if not all([title, source, digest, content, index_image, category_id]):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

        try:
            index_image_data = index_image.read()
        except Exception as e:
            current_app.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

        # 3.3 上传新闻图⽚
        try:
            key = upload_file(index_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.THIRDERR, errmsg='上传图⽚片失败')

        # 3.4 存储新闻数据
        news = News()
        news.title = title
        news.digest = digest
        news.source = source
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.user_id = user.id
        # 1代表待审核状态
        news.status = 1

        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmsg='保存发布新闻数据失败')

        # 3.5 响应发布结果
        return jsonify(errno=response_code.RET.OK, errmsg='发布新闻成功')


@user_blue.route('/user_collection')
@user_login_data
def user_collection():
    """个人收藏"""
    # 1.获取user信息
    user = g.user

    # 2.查询展示用户收藏的新闻列表，并分页
    # 2.1 接受参数：当前看第几页
    page = request.args.get('p', 1)

    # 2.2 校验参数：判断参数是否是整数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3.查询登录用户收藏的新闻数据
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {
        'news_dict_list': news_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_collection.html', context=context)


@user_blue.route('/pass_info', methods=['get', 'post'])
@user_login_data
def pass_info():
    """修改密码"""
    # 1.获取user信息
    user = g.user

    # 2.展示修改密码页面逻辑：GET
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 3.实现修改密码逻辑：POST
    if request.method == 'POST':

        # 3.1接收参数
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')

        # 3.2 校验参数：判断参数是否齐全，判断old_password是否是当前登录用户的原始密码
        if not all([old_password, new_password]):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
        if not user.check_password(old_password):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='旧密码参数')

        # 3.3 将新的密码同步到数据库(核心代码)
        user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.rollback()
            return jsonify(errno=response_code.RET.DATAERR, errmsg='保存新密码失败')

        # 3.5.响应修改结果
        return jsonify(errno=response_code.RET.OK, errmsg='密码修改成功')


@user_blue.route('/pic_info', methods=['get', 'post'])
@user_login_data
def pic_info():
    """用户头像上传"""
    # 1.获取user信息
    user = g.user

    # 2.渲染用户头像界⾯
    if request.method == 'GET':
        context = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', context=context)
    # 2.2修改用户基本资料逻辑：post
    if request.method == 'POST':
        # 3.1接收参数
        # request.files : 读取表单中的文件信息
        # request.form : 读取表单中的文字信息
        avatar_file = request.files.get('avatar')  # avatar_file ：是文件对象，FileStorage类型的

        # 3.2 校验参数：判断文件二进制是否成功传送给来
        try:
            # read() ： 读取文件对象的二进制信息
            avatar_data = avatar_file.read()
        except Exception as e:
            current_app.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

        # 3.3 调用风封装七牛云的上传方法，将文件二进制数据上传到七牛云（核心代码）
        try:
            key = upload_file(avatar_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.THIRDERR, errmsg='上传文件到七牛云失败')

        # 3.4 将七牛元返回的唯一标识存储到数据库，跟user绑定（核心代码）
        user.avatar_url = key
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.roolback()
            return jsonify(errno=response_code.RET.DATAERR, errmsg='保存用户头像失败')

        # 3.5 返回上传头像之后的结果
        data = {
            'avatar_url': constants.QINIU_DOMIN_PREFIX + key
        }
        return jsonify(errno=response_code.RET.OK, errmsg='上传头像成功', data=data)


@user_blue.route('/info')
@user_login_data
def user_info():
    """个人中心入口"""
    # 1.判断用户是否登录
    user = g.user
    if not user:
        # 如果⽤用户未登录，重定向到index蓝图中的index视图
        return redirect(url_for('index.index'))
    context = {
        'user': user.to_dict()
    }
    # 渲染个人中心入口模板
    return render_template('news/user.html', context=context)


@user_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    """基本资料"""
    # 1.判断用户是否登录
    user = g.user
    # 2.渲染用户基本信息界面
    # 2.1查询用户基本信息
    if request.method == 'GET':
        context = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', context=context)

    # 2.2修改用户基本资料逻辑：post
    if request.method == 'POST':

        # 3.1接收参数 个性签名 用户昵称 性别
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        # 3.2校验参数
        if not all([nick_name, signature, gender]):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
        if gender not in ['MAN', 'WOMAN']:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

        # 3.3修改用户数据
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender

        # 3.4同步到数据库
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmsg='更新资料失败')

        # 注意点：如果修改了昵称，需修改状态保持里的昵称
        # session['nick_name'] = nick_name

        # 3.5响应修改结果
        return jsonify(errno=response_code.RET.OK, errmsg='更新资料成功')
